// @flow
import React from 'react'
import { Form, Input, Button, message, Upload, Icon } from 'antd'
import universalFetch, { handleFetchError } from 'store/modules/fetch'
const FormItem = Form.Item
import styles from './UserEdit.css'
const formItemLayout = {
  labelCol: {
    xs: { span: 24 },
    sm: { span: 6 }
  },
  wrapperCol: {
    xs: { span: 24 },
    sm: { span: 14 }
  }
}
const tailFormItemLayout = {
  wrapperCol: {
    xs: {
      span: 24,
      offset: 0
    },
    sm: {
      span: 14,
      offset: 6
    }
  }
}

type Props = {
  history: Object,
  form: Object,
  data: Object,
  onCancel: Function
}

type State = {
  userRoles: Array<Object>,
  imageUrl: string,
  remoteImageUrl: string
}

class UserEdit extends React.Component {
  props: Props
  state: State
  submit: Function
  changeFile: Function
  beforeUpload: Function
  constructor (props: Props) {
    super(props)
    this.state = {
      userRoles: [],
      imageUrl: '',
      remoteImageUrl: ''
    }

    this.submit = this.submit.bind(this)
    this.changeFile = this.changeFile.bind(this)
    this.beforeUpload = this.beforeUpload.bind(this)
  }

  componentWillMount () {
    const { data } = this.props
    let imageUrl = data.photo
    if (imageUrl) {
      const index = imageUrl.lastIndexOf('/')
      imageUrl = imageUrl.substring(index + 1, imageUrl.length)
      this.setState({
        imageUrl: imageUrl,
        remoteImageUrl: data.photo
      })
    }
  }

  changeFile (info) {
    const response = info.file.response
    if (response && response.code === 200000) {
      this.setState({
        imageUrl: response.result.name,
        remoteImageUrl: response.result.url
      })
    }
  }

  beforeUpload (file) {
    const type = file.type.toLocaleLowerCase()
    if (type.indexOf('image/') === -1) {
      message.error('只能上传图片', 3)
    }
    const isLt2M = file.size / 1024 / 1024 < 2
    if (!isLt2M) {
      message.error('图片必须小于2MB!')
    }
    return type.indexOf('image/') > -1
  }

  submit () {
    const { form, data } = this.props
    form.validateFields((err, fieldsValue) => {
      if (err) {
        return false
      }
      const { imageUrl } = this.state
      let values = {
        ...Object.assign({}, fieldsValue, { photo: imageUrl })
      }
      universalFetch(`${__SERVICE_API__}sys/users/${data.id}`,
        {
          method: 'PUT',
          headers: {
            'Content-Type': 'application/json',
            'Accept': 'application/json'
          },
          body: JSON.stringify(values)
        })
        .then((res) => res.json())
        .then((json) => {
          if (json.code !== 200000) {
            throw new Error(JSON.stringify({ code: json.code, message: json.message }))
          }
          message.success('修改成功')
          this.props.onCancel()
        })
        .catch((error) => {
          handleFetchError(error)
          console.error(error)
          message.error('修改失败')
        })
    })
  }

  render () {
    const { getFieldDecorator } = this.props.form
    const { remoteImageUrl } = this.state
    const { data } = this.props
    const token = localStorage.getItem('asset_token')
    return (
      <div className={styles['main']}>
        <Form>

          <FormItem
            {...formItemLayout}
            label='昵称'
            hasFeedback
          >
            {getFieldDecorator('name', {
              rules: [{ required: true, message: '请填写昵称', whitespace: true }],
              initialValue: data.name
            })(
              <Input placeholder='请填写昵称' />
              )}
          </FormItem>
          <FormItem {...formItemLayout} label='手机号' hasFeedback>
            {
              getFieldDecorator('mobile', {
                rules: [
                  { required: true, message: '请填写手机号', whitespace: true }
                ],
                initialValue: data.mobile
              })(
                <Input placeholder='请填写手机号' />
              )
            }
          </FormItem>

          <FormItem {...formItemLayout} label='邮箱' hasFeedback>
            {
              getFieldDecorator('email', {
                rules: [
                  { required: true, message: '请填写邮箱' }
                ],
                initialValue: data.email
              })(
                <Input placeholder='请填写邮箱' />
              )
            }
          </FormItem>
          <FormItem {...formItemLayout} label='用户类型' hasFeedback>
            {
              getFieldDecorator('userType', {
                initialValue: data.userType
              })(
                <Input placeholder='请填写用户类型' />
              )
            }
          </FormItem>
          <FormItem {...formItemLayout} label='用户头像'>
            {
              getFieldDecorator('photo', { initialValue: data.photo })(
                <Upload
                  {...{
                    name: 'file',
                    className: styles['avatar-uploader'],
                    action: `${__SERVICE_API__}static/statics`,
                    headers:{ 'X-Auth':token },
                    onChange: this.changeFile,
                    beforeUpload: this.beforeUpload,
                    showUploadList: false
                  }}
                  >
                  {
                    remoteImageUrl
                    ? <div className={styles['image-preview']}>
                      <img src={remoteImageUrl} style={{ width: '100%' }} />
                      <div className={styles['over-avatar']}>
                        更换图片
                      </div>
                    </div>
                    : <Button style={{ width: '150px' }}>
                      <Icon type='upload' />上传图片
                    </Button>
                  }
                </Upload>
              )
            }
          </FormItem>
          <FormItem
            {...tailFormItemLayout}
            className={styles['footbtn']}
          >
            <Button type='primary'
              className='login-form-button'
              onClick={this.submit}
              >
              提交
            </Button>
            <Button style={{ marginLeft: '20px' }}
              onClick={this.props.onCancel}
              >
              返回
            </Button>
          </FormItem>
        </Form>
      </div>
    )
  }
}
export default Form.create()(UserEdit)
